import Foundation
import Vapor

struct COSServiceProxy {
    let baseURL: String
    let httpClient: Client
    
    init(baseURL: String, httpClient: Client) {
        self.baseURL = baseURL
        self.httpClient = httpClient
    }
    
    // 生成唯一的文件名
    func generateUniqueFileName(userId: UUID, fileExtension: String) async throws -> String {
        let url = URI(string: "\(baseURL)/generate_unique_filename")
        
        struct Request: Content {
            let userId: String
            let fileExtension: String
        }
        
        struct Response: Content {
            let fileName: String
        }
        
        let request = Request(userId: userId.uuidString, fileExtension: fileExtension)
        let response = try await httpClient.post(url) { req in
            try req.content.encode(request)
        }
        
        let result = try response.content.decode(Response.self)
        return result.fileName
    }
    
    // 生成预签名上传URL
    func generatePresignedUrl(
        for fileName: String,
        fileType: String,
        contentMD5: String? = nil,
        expiresIn seconds: Int = 3600
    ) async throws -> String {
        let url = URI(string: "\(baseURL)/generate_presigned_url")
        
        struct Request: Content {
            let fileName: String
            let fileType: String
            let contentMD5: String?
            let expiresIn: Int
        }
        
        struct Response: Content {
            let uploadURL: String
        }
        
        let request = Request(
            fileName: fileName,
            fileType: fileType,
            contentMD5: contentMD5,
            expiresIn: seconds
        )
        
        let response = try await httpClient.post(url) { req in
            try req.content.encode(request)
        }
        
        let result = try response.content.decode(Response.self)
        return result.uploadURL
    }
    
    // 生成头像访问URL
    func generateAvatarUrl(
        for avatarKey: String,
        size: String? = nil,
        expiresIn seconds: Int = 7200
    ) async throws -> String {
        let url = URI(string: "\(baseURL)/generate_avatar_url")
        
        struct Request: Content {
            let avatarKey: String
            let size: String?
            let expiresIn: Int
        }
        
        struct Response: Content {
            let avatarUrl: String
        }
        
        let request = Request(avatarKey: avatarKey, size: size, expiresIn: seconds)
        let response = try await httpClient.post(url) { req in
            try req.content.encode(request)
        }
        
        let result = try response.content.decode(Response.self)
        return result.avatarUrl
    }
    
    // 根据用户选择的区域裁剪头像
    func cropAvatar(
        for avatarKey: String,
        cropRegion: [String: Int],
        targetSize: Int? = nil,
        rotate: Int? = nil,
        expiresIn seconds: Int = 7200
    ) async throws -> AvatarCropResult {
        let url = URI(string: "\(baseURL)/crop_avatar")
        
        struct Request: Content {
            let avatarKey: String
            let cropRegion: [String: Int]
            let targetSize: Int?
            let rotate: Int?
            let expiresIn: Int
        }
        
        let request = Request(
            avatarKey: avatarKey,
            cropRegion: cropRegion,
            targetSize: targetSize,
            rotate: rotate,
            expiresIn: seconds
        )
        
        let response = try await httpClient.post(url) { req in
            try req.content.encode(request)
        }
        
        let result = try response.content.decode(AvatarCropResult.self)
        return result
    }
    
    // 处理头像并返回多种尺寸
    func processAvatar(
        for avatarKey: String,
        size: String? = nil,
        expiresIn seconds: Int = 7200
    ) async throws -> AvatarProcessResult {
        let url = URI(string: "\(baseURL)/process_avatar")
        
        struct Request: Content {
            let avatarKey: String
            let size: String?
            let expiresIn: Int
        }
        
        let request = Request(
            avatarKey: avatarKey,
            size: size,
            expiresIn: seconds
        )
        
        let response = try await httpClient.post(url) { req in
            try req.content.encode(request)
        }
        
        let result = try response.content.decode(AvatarProcessResult.self)
        return result
    }
    
    // 旋转头像
    func rotateAvatar(
        for avatarKey: String,
        angle: Int,
        targetSize: Int? = nil,
        expiresIn seconds: Int = 7200
    ) async throws -> AvatarCropResult {
        let url = URI(string: "\(baseURL)/rotate_avatar")
        
        struct Request: Content {
            let avatarKey: String
            let angle: Int
            let targetSize: Int?
            let expiresIn: Int
        }
        
        let request = Request(
            avatarKey: avatarKey,
            angle: angle,
            targetSize: targetSize,
            expiresIn: seconds
        )
        
        let response = try await httpClient.post(url) { req in
            try req.content.encode(request)
        }
        
        let result = try response.content.decode(AvatarCropResult.self)
        return result
    }
}

// 头像裁剪结果结构
struct AvatarCropResult: Content {
    let success: Bool
    let message: String
    let avatarUrl: String
    let avatarUrls: [String: String]
}

// 头像处理结果结构
struct AvatarProcessResult: Content {
    let success: Bool
    let message: String
    let originalAvatarUrl: String
    let avatarUrl: String
    let avatarUrls: [String: String]
}

// 扩展Application
extension Application {
    private struct COSServiceProxyKey: StorageKey {
        typealias Value = COSServiceProxy
    }
    
    var cosServiceProxy: COSServiceProxy {
        get {
            guard let service = storage[COSServiceProxyKey.self] else {
                fatalError("COS服务代理尚未配置，请在configure中配置")
            }
            return service
        }
        set {
            storage[COSServiceProxyKey.self] = newValue
        }
    }
}

// 扩展Request
extension Request {
    var cosServiceProxy: COSServiceProxy {
        application.cosServiceProxy
    }
} 